package com.imay.live.adapter.holder;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.imay.live.R;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.cache.UserInfoCache;
import com.imay.live.fragment.dynamics.OnTouchHeartListener;
import com.imay.live.helper.LevelHelper;
import com.imay.live.helper.LocationHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.model.FeedModel;
import com.imay.live.model.UserInfoModel;
import com.imay.live.model.UserModel;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.GlideUtil;
import com.imay.base.util.SpannableStringUtils;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by chan on 2017/4/6.
 */

public class DynamicsViewHolder {
    private boolean visiableFeed;//是否展示关注按钮
    private LocationHelper locationHelper;
    long myuid;

    public DynamicsViewHolder(boolean visiableFeed) {
        this.visiableFeed = visiableFeed;
        locationHelper = LocationHelper.getInstance();
        UserInfoModel userInfoModel = UserInfoCache.getUserInfo();
        if (userInfoModel != null && userInfoModel.getUser() != null) {
            myuid = userInfoModel.getUser().getUid();
        }
    }

    // 执行图片
    public void convertImg(final BaseViewHolder helper, final FeedModel item, final OnTouchHeartListener listener) {
        final Context mContext = helper.getConvertView().getContext().getApplicationContext();
        // 图片
        ImageView imageView = helper.getView(R.id.iv_item_content_img);
        imageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motion) {
                if (motion.getAction() == MotionEvent.ACTION_UP) {
                    if (listener != null) {
                        MobclickAgent.onEvent(mContext, "feed_click_content");
                        listener.showHeart(motion.getRawX(), motion.getRawY(), item.getFeedId(), true);
                        if (!item.isIsLike()) {
                            final ImageView mHeart = helper.getView(R.id.iv_item_dongtai_content_des_heart);
                            mHeart.setSelected(true);
                            item.setIsLike(true);
                            item.setCountLike(item.getCountLike() + 1);
                            helper.setText(R.id.tv_item_dongtai_content_des_heart_text, mContext.getApplicationContext().getString(R.string.str_dynamics_like_text, item.getCountLike()));
                        }
                    }
                }
                return true;
            }
        });


        if (item.getRepostedFeed() != null && item.getRepostedFeed().getUid() == 0) {
            helper.setImageResource(R.id.iv_item_content_img, R.mipmap.ico_01_nodata);
        } else {
            GlideUtil.loadImage((ImageView) helper.getView(R.id.iv_item_content_img), item.getImgUrl() + "?imageslim", R.mipmap.placeholder);
        }


        // 执行公共部分
        convert(helper, item, listener);
    }

    // 执行视频
    public void convertMov(BaseViewHolder helper, final FeedModel item, final OnTouchHeartListener listener) {
        final Context mContext = helper.getConvertView().getContext().getApplicationContext();
        RelativeLayout mRlDynamics = helper.getView(R.id.rl_dynamics_content);

        // 图片
        ImageView mImageView = helper.getView(R.id.iv_item_content_img);
        if (item.getRepostedFeed() != null && item.getRepostedFeed().getUid() == 0) {
            helper.setImageResource(R.id.iv_item_content_img, R.mipmap.ico_01_nodata);
        } else {
            GlideUtil.loadImage((ImageView) helper.getView(R.id.iv_item_content_img), UrlHelper.getVideoThumbUrl(item.getVideoUrl()), R.mipmap.placeholder);
        }
        mImageView.setVisibility(View.VISIBLE);


        final ImageView iv_item_content_video_player = helper.getView(R.id.iv_item_content_video_player);
        iv_item_content_video_player.setAlpha(80);

        final ImageView mIvVoice = helper.getView(R.id.iv_item_content_video_voice);
        mImageView.setSelected(false);
        mIvVoice.setTag(false);
        final BaseViewHolder helper1 = helper;
        mIvVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (listener != null) {
                    listener.onVoiceClick(helper1.getLayoutPosition());
                }
            }
        });

        final GestureDetector mGestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapConfirmed(MotionEvent e) {
                if (listener != null) {
                    mIvVoice.callOnClick();
                }
                return false;
            }

            @Override
            public boolean onDoubleTap(MotionEvent event) {
                if (listener != null) {
                    listener.showHeart(event.getRawX(), event.getRawY(), item.getFeedId(), true);
                    if (!item.isIsLike()) {
                        final ImageView mHeart = helper1.getView(R.id.iv_item_dongtai_content_des_heart);
                        mHeart.setSelected(true);
                        item.setIsLike(true);
                        item.setCountLike(item.getCountLike() + 1);
                        helper1.setText(R.id.tv_item_dongtai_content_des_heart_text, mContext.getApplicationContext().getString(R.string.str_dynamics_like_text, item.getCountLike()));
                    }
                }
                return false;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                return false;
            }
        });


        mRlDynamics.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                mGestureDetector.onTouchEvent(event);
                return true;
            }
        });

        // 执行公共部分
        convert(helper, item, listener);
    }

    // @用户点击方法 采用富文本点击
    private ClickableSpan atClick(final Context context, final UserModel userBean, final OnTouchHeartListener listener) {
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                if (listener != null) {
                    listener.atClick(userBean.getNick(), userBean.getUid());
                }
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(context.getResources().getColor(R.color.text_30));
                ds.setUnderlineText(false);
                ds.clearShadowLayer();
            }
        };
        return clickableSpan;
    }

    // @用户点击方法 采用富文本点击
    private ClickableSpan reportAtClick(final Context context, final UserModel userBean, final OnTouchHeartListener listener) {
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                if (listener != null) {
                    listener.atClick(userBean.getNick(), userBean.getUid());
                }
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.BLACK);
                ds.setUnderlineText(false);
                ds.clearShadowLayer();
            }
        };
        return clickableSpan;
    }

    // #话题点击方法 采用富文本点击
    private ClickableSpan jinClick(final Context context, final String label, final OnTouchHeartListener listener) {
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                //Do something.
                if (listener != null) {
                    listener.jinClick(label);
                }
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(context.getResources().getColor(R.color.text_30));
                ds.setUnderlineText(false);
                ds.clearShadowLayer();
            }
        };
        return clickableSpan;
    }


    // 公共部分
    private void convert(final BaseViewHolder helper, final FeedModel item, final OnTouchHeartListener listener) {
        final Context mContext = helper.getConvertView().getContext().getApplicationContext();

        if (item.getFamilyId() == 0 || item.getInternalPublic() == 0) {
            helper.setVisible(R.id.iv_item_content_family_icon, false);
        } else {
            helper.setVisible(R.id.iv_item_content_family_icon, true);
        }

        Pattern pattern = Pattern.compile("@([^@#\\s]+)|#([^@#\\s]+)");

        // 直播数
        helper.setVisible(R.id.tv_item_content_live_num, false);

        // VIP的显示图标
        int vip = 0;
        if (item.getUser() != null) {
            vip = item.getUser().getVip();
        }
        int icon = LevelHelper.getVIPIcon(vip);
        if (icon == 0) {
            helper.setVisible(R.id.iv_item_content_vip, false);
        } else {
            helper.setVisible(R.id.iv_item_content_vip, true);
            helper.setImageResource(R.id.iv_item_content_vip, icon);
        }

        /**
         * part2 内容
         */
        String des = item.getMsg();
        if (TextUtils.isEmpty(des)) {
            helper.setVisible(R.id.tv_item_dongtai_content_des, false);
        } else {
            if (des.equals("(null)")) {
                helper.setVisible(R.id.tv_item_dongtai_content_des, false);
            } else {
                Matcher matcher = pattern.matcher(des);
                helper.setVisible(R.id.tv_item_dongtai_content_des, true);

                TextView mContentDes = helper.getView(R.id.tv_item_dongtai_content_des);
                set(item, listener, mContext, des, matcher, mContentDes);
            }
        }

        /**
         * part1
         */
        // 地址
        boolean isShowJuli = true;
        String city = item.getCity();
        if (city == null || city.equals("") || city.equals("(null)")) {
            isShowJuli = false;
            city = mContext.getString(R.string.str_dynamics_address);
        }
        helper.setText(R.id.tv_item_content_adress, city);

        // 名字与头像 && 性别
        UserModel userBean = item.getUser();
        if (userBean != null) {
            helper.setText(R.id.tv_item_content_name, userBean.getNick());
            ImageView civ_item_content_img = helper.getView(R.id.civ_item_content_img);
            GlideUtil.loadCircleImage(civ_item_content_img, userBean.getImgHead(), R.mipmap.pnl_00_head108);
            if (userBean.getSex() == 1) {
                helper.setImageResource(R.id.iv_item_icon_sex, R.mipmap.ico_00boy);
            } else if (userBean.getSex() == 2) {
                helper.setImageResource(R.id.iv_item_icon_sex, R.mipmap.ico_00girl);
            }
            if (visiableFeed) {
                helper.addOnClickListener(R.id.tv_dynfllow);
                if (userBean.isMyFollow()) {
                    helper.setVisible(R.id.tv_dynfllow, false);
                    helper.setTextColor(R.id.tv_dynfllow, helper.getConvertView().getResources().getColor(R.color.text_b2));
                    helper.setText(R.id.tv_dynfllow, helper.getConvertView().getResources().getString(R.string.has_followed));
                    helper.setBackgroundRes(R.id.tv_dynfllow, R.drawable.shape_corner5_white_bc);
                } else {
                    if (userBean.getUid() == myuid) {
                        helper.setVisible(R.id.tv_dynfllow, false);
                    } else {
                        helper.setVisible(R.id.tv_dynfllow, true);
                    }
                    helper.addOnClickListener(R.id.tv_dynfllow);
                    helper.setTextColor(R.id.tv_dynfllow, helper.getConvertView().getResources().getColor(R.color.color_ff));
                    helper.setText(R.id.tv_dynfllow, helper.getConvertView().getResources().getString(R.string.un_followed));
                    helper.setBackgroundRes(R.id.tv_dynfllow, R.drawable.shape_corner100_white_ff0);
                }
            }

        }

        // 时间
        long localTime = System.currentTimeMillis();
        // java乘于1000
        long createTime = item.getCreateTime();
        long diff = (localTime - (createTime * 1000L));
        long days = diff / (1000 * 60 * 60 * 24);
        long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
        helper.setText(R.id.tv_item_content_time, AppUtil.getTimeStr(mContext, days, hours, minutes));

        final double longtitude = locationHelper.getLongitude();
        final double latitude = locationHelper.getLatitude();
        if (!isShowJuli || item.getLongitude() == 0.0 || item.getLatitude() == 0.0 || latitude == 0.0 || longtitude == 0.0) {
            helper.setVisible(R.id.tv_item_content_adress_juli, false);
        } else {
            helper.setVisible(R.id.tv_item_content_adress_juli, true);
            double distance = AppUtil.gps2m(latitude, longtitude, item.getLatitude() / 1000000D, item.getLongitude() / 1000000D);
            distance = distance / 1000D;
            if (distance < 0.5) {
                distance = 0.5;
                helper.setText(R.id.tv_item_content_adress_juli, mContext.getString(R.string.str_dynamics_distance, Double.toString(distance)));
            } else if (distance > 0.5 && distance < 10) {
                distance = changeDouble(distance);
                helper.setText(R.id.tv_item_content_adress_juli, mContext.getString(R.string.str_dynamics_distance, Double.toString(distance)));
            } else {
                int d = (int) distance;
                helper.setText(R.id.tv_item_content_adress_juli, mContext.getString(R.string.str_dynamics_distance, Integer.toString(d)));
            }
        }

        // like
        helper.setText(R.id.tv_item_dongtai_content_des_heart_text, mContext.getApplicationContext().getString(R.string.str_dynamics_like_text, item.getCountLike()));
        // 评论
        helper.setText(R.id.tv_item_dongtai_content_des_pinglun_text, mContext.getApplicationContext().getString(R.string.str_dynamics_comment_text, item.getCountComment()));


        /**
         * part3
         */
        final ImageView mHeart = helper.getView(R.id.iv_item_dongtai_content_des_heart);
        if (item.isIsLike()) {
            mHeart.setSelected(true);
        } else {
            mHeart.setSelected(false);
        }
        mHeart.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motion) {
                if (motion.getAction() == MotionEvent.ACTION_UP) {
                    MobclickAgent.onEvent(mContext, "feed_click_content");
                    if (listener != null) {
                        if (item.isIsLike()) {
                            item.setCountLike(item.getCountLike() - 1);
                            mHeart.setSelected(false);
                            item.setIsLike(false);
                            listener.showHeart(motion.getRawX(), motion.getRawY(), item.getFeedId(), false);
                        } else {
                            item.setCountLike(item.getCountLike() + 1);
                            mHeart.setSelected(true);
                            item.setIsLike(true);
                            listener.showHeart(motion.getRawX(), motion.getRawY(), item.getFeedId(), true);
                        }
                        helper.setText(R.id.tv_item_dongtai_content_des_heart_text, mContext.getApplicationContext().getString(R.string.str_dynamics_like_text, item.getCountLike()));
                    }
                }
                return true;
            }
        });


        // 转发
        FeedModel repostedFeedModel = item.getRepostedFeed();
        if (repostedFeedModel != null && repostedFeedModel.getUser() != null) {
            UserModel bean = repostedFeedModel.getUser();
            if (bean != null) {
                helper.setVisible(R.id.tv_dynamics_content_part5_username, true);
                String string = "@" + bean.getNick();
                TextView mAtUserRepost = helper.getView(R.id.tv_dynamics_content_part5_username);
                mAtUserRepost.setText(SpannableStringUtils.getBuilder(string).setBold().setClickSpan(reportAtClick(mContext, bean, listener)).create());
                mAtUserRepost.setMovementMethod(LinkMovementMethod.getInstance());

                String msg = repostedFeedModel.getMsg();
                if (repostedFeedModel.getAtUsers() != null && repostedFeedModel.getLabels() != null) {
                    if (TextUtils.isEmpty(msg)) {
                        for (UserModel userModel : repostedFeedModel.getAtUsers()) {
                            msg = msg + " @" + userModel.getNick();
                        }
                        for (String label : repostedFeedModel.getLabels()) {
                            msg = msg + " #" + label;
                        }
                    } else if (!TextUtils.isEmpty(msg) && (!msg.contains("#") && !msg.contains("@"))) {
                        for (UserModel userModel : repostedFeedModel.getAtUsers()) {
                            msg = msg + " @" + userModel.getNick();
                        }
                        for (String label : repostedFeedModel.getLabels()) {
                            msg = msg + " #" + label;
                        }
                    }
                }

                if (TextUtils.isEmpty(msg) || msg.equals("(null)")) {
                    helper.setVisible(R.id.ll_dynamics_content_part5_text, false);
                } else {
                    helper.setVisible(R.id.ll_dynamics_content_part5_text, true);

                    Matcher matcher = pattern.matcher(msg);

                    TextView mContentDes = helper.getView(R.id.tv_dynamics_content_part5_text);
                    set(repostedFeedModel, listener, mContext, msg, matcher, mContentDes);
                }
                helper.setVisible(R.id.rl_dynamics_content_part5, true);
            } else {
                helper.setVisible(R.id.rl_dynamics_content_part5, false);
            }
        } else {
            helper.setVisible(R.id.rl_dynamics_content_part5, false);
        }

        // 点击事件
        helper.addOnClickListener(R.id.tv_item_content_name);
        helper.addOnClickListener(R.id.civ_item_content_img);
        helper.addOnClickListener(R.id.iv_item_dongtai_content_des_qita);       // 其他 举报
        helper.addOnClickListener(R.id.tv_item_dongtai_content_des_heart_text);
        helper.addOnClickListener(R.id.iv_item_dongtai_content_des_pinglun);
        helper.addOnClickListener(R.id.tv_item_dongtai_content_des_pinglun_text);
    }

    /**
     * 保留一位小数
     *
     * @param dou
     * @return
     */
    public double changeDouble(Double dou) {
        NumberFormat nf = new DecimalFormat("0.0");
        dou = Double.parseDouble(nf.format(dou));
        return dou;
    }

    /**
     * 执行 富文本
     *
     * @param item
     * @param listener
     * @param mContext
     * @param des
     * @param matcher
     * @param mContentDes
     */
    private void set(FeedModel item, OnTouchHeartListener listener, Context mContext, String des, Matcher matcher, TextView mContentDes) {
        List<UserModel> userAtBeans = item.getAtUsers();
        List<String> labels = item.getLabels();

        SpannableString string = new SpannableString(des);
        int start;
        int end = 0;
        while (matcher.find(end)) {
            boolean c = false;
            start = matcher.start();
            end = matcher.end();
            if (userAtBeans != null) {
                for (UserModel userBean : userAtBeans) {
                    String nick = mContext.getString(R.string.str_dynamics_at_text, userBean.getNick());
                    if (matcher.group().equals(nick)) {
                        string.setSpan(atClick(mContext, userBean, listener), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                        c = true;
                        break;
                    }
                }
            }

            // 防止循环操作相同的
            if (c) {
                continue;
            }

            if (labels != null) {
                for (String label : labels) {
                    String labelText = mContext.getString(R.string.str_dynamics_jin_text, label);
                    if (matcher.group().equals(labelText)) {
                        string.setSpan(jinClick(mContext, label, listener), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                        break;
                    }
                }
            }
        }

        mContentDes.setText(string);
        mContentDes.setMovementMethod(LinkMovementMethod.getInstance());
    }
}
